﻿using System;
using System.Collections.Generic;
using JetBrains.Annotations;
using UnityEngine;

namespace Level
{
    public class GameStateMachine : MonoBehaviour
    {
        [CanBeNull]
        private IState CurrentState
        {
            get
            {
                if (_currentStateType is null)
                {
                    return null;
                }

                return _stateMap[_currentStateType];
            }
        }
        
        private readonly Dictionary<Type, IState> _stateMap = new();
        
        private Type _previousStateType;
        private Type _currentStateType;


        private void Awake()
        {
            AddState<GameStartedState>();
            AddState<GameOverState>();
            AddState<PauseState>();
        }

        private void Start()
        {
            SwitchState<GameStartedState>();
        }

        private void OnDestroy()
        {
            CurrentState?.Exit();
        }

        public void SwitchState<TState>()
        {
            Debug.Log($"State: {typeof(TState)}");
            
            CurrentState?.Exit();
            _previousStateType = _currentStateType;
            _currentStateType = typeof(TState);
            CurrentState?.Enter();
        }

        private void AddState<TState>()
            where TState : IState
        {
            _stateMap.Add(typeof(TState), GetComponent<TState>().Init(this));
        }
    }
}